package com.thread.threadfirst.studyThread2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 1、reentrantlock：
 * 注意：使用Lock必须手动释放锁
 * 使用synchronized锁定的话，遇到异常，jvm会自动释放锁，而lock必须手动释放锁，因此经常在finally中进行释放锁。
 */
public class T {
    Lock lock = new ReentrantLock();

    void m1() {
        try {
            lock.lock();
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void m2() {
        lock.lock();
        System.out.println("m2……");
        lock.unlock();
    }

    public static void main(String[] args) {
        T t = new T();
        new Thread(() -> t.m1()).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(t::m2).start();
    }

}
